package mq.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 产生RabbitMQ 信道
 *
 * @author verlet
 * @date 2019/9/13
 */
public class RabbitMqChannelFactory {

    public static Channel createChannel() throws IOException, TimeoutException {
        // 创建一个ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");
        // 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        // 通过connection创建一个channel
        return connection.createChannel();
    }

    public static void close(Channel channel) throws IOException, TimeoutException {
        if (channel != null) {
            Connection connection = channel.getConnection();
            channel.close();
            connection.close();
        }
    }
}
